﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Automapping;
using System.Reflection;

namespace Atomic.Db
{
    public sealed class HibernateHelper
    {
        static ISessionFactory sf;
        public static FluentConfiguration fc;

        static HibernateHelper()
        {
            try
            {
                //TODO：临时建立，需要替换到配置文件中去实现
                List<string> dlls = new List<string>()
                {
                    "Atomic.Permission.dll",
                    "Atomic.User.dll",
                    "Atomic.Configuration.dll",
                    "Atomic.FriendLink.dll"
                };
                fc = Fluently.Configure();
                fc=fc.Database(MsSqlConfiguration.MsSql2008.ConnectionString("Data Source=.;Initial Catalog=Atomic;Integrated Security=True;MultipleActiveResultSets=True"));

                //加载程序集的到配置
                fc = fc.Mappings(
                        m =>
                        {
                            //加载映射
                            foreach (string item in dlls)
                            {
                                m.FluentMappings.AddFromAssembly(Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "/bin/" + item));
                            }
                        }
                    );
                
                //构建Session工厂
                sf = fc.BuildSessionFactory();
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static ISession GetSession()
        {
            try
            {
                return sf.OpenSession();
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
